<?php

namespace App\Http\Requests\dispatch;

use App\Http\ValidateResult;
use App\Models\DispatchTaskModel;
use Illuminate\Support\Facades\Validator;

trait TaskRequest
{
    public static function add_check(array $params): ValidateResult {
        $validator = Validator::make($params, [
            'load_date' => 'required|date_format:Y-m-d',
            'type_id' => 'required',
            'car_id' => 'required|integer',
            'agent_id' => 'required|integer',
            'feng_id' => 'required|integer',
            'load_warehouse_ids' => 'required|array',
            'unload_warehouse_ids' => 'required|array',
//            'driver_id' => 'required|integer',
//            'hk_driver_id' => 'required|integer',
        ], [
            'load_date.required' => '请选择装车日期',
            'type_id.required' => '请选择车辆类型',
            'car_id.required' => '请选择车辆',
            'car_id.integer' => '车辆ID必须是整数',
            'agent_id.required' => '请选择代理商',
            'agent_id.integer' => '代理商ID必须是整数',
            'feng_id.required' => '请选择关场口岸',
            'feng_id.integer' => '关场口岸ID必须是整数',
            'load_warehouse_ids.required' => '请选择装车地',
            'load_warehouse_ids.array' => '装车地错误',
            'unload_warehouse_ids.required' => '请选择卸货地',
            'unload_warehouse_ids.array' => '卸货地错误',
        ]);

        if ($validator->fails()) {
            return ValidateResult::error($validator->errors()->first());
        }
        return ValidateResult::correct();
    }


    public static function cost_check(array $params): ValidateResult {
        $validator = Validator::make($params, [
            'costs' => 'required|array',
        ], [
            'cost.required' => '请填写运输成本',
            'cost.array' => '运输成本格式错误'
        ]);
        if ($validator->fails()) {
            return ValidateResult::error($validator->errors()->first());
        }

        /**
         *  {
         *   "subject_id": 1, //费用(科目)id, 不能重复
         *   "amount": 1.23,  //费用
         *   "currency_id": 1, //币种id
         *   "remark": "备注"
         *  },
         */
        foreach($params['costs'] as $cost)  {
            $validator = Validator::make($cost, [
                'subject_id' => 'required|integer',
                'amount' => 'required|numeric',
                'currency_id' => 'required|integer',
            ], [
                'subject_id.required' => '请填写费用科目',
                'subject_id.integer' => '费用科目必须是整数',
                'amount.required' => '请填写费用金额',
                'amount.numeric' => '费用金额必须是数字',
                'currency_id.required' => '请填写币种',
                'currency_id.integer' => '币种必须是整数',
            ]);
            if ($validator->fails()) {
                return ValidateResult::error($validator->errors()->first());
            }
        }

        return ValidateResult::correct();
    }

}
